package com.mengtian_tech.smart_farm.controller;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.fasterxml.jackson.annotation.JsonView;
import com.mengtian_tech.smart_farm.model.FarmWork;
import com.mengtian_tech.smart_farm.service.SystemService;
import com.mengtian_tech.smart_farm.vo.AjaxJson;
import com.mengtian_tech.smart_farm.vo.JsonViews;
import com.mengtian_tech.smart_farm.vo.PageResult;
import com.mengtian_tech.smart_farm.vo.Query;

/**
 * 农事管理控制器
 * @author wxd56
 *
 */
@Controller
@RequestMapping("scgl/farmWork/")
public class FarmWorkController {
	
	@Autowired
	SystemService systemService;
	
	@RequestMapping("list")
	@ResponseBody
	@JsonView(JsonViews.FarmWorkList.class)
	public AjaxJson list(@RequestBody(required = false) FarmWork work) {
		if(work == null) {
			work = new FarmWork();
		}
		Query<FarmWork> q = Query.create(work);
		PageResult<FarmWork> pageResult =  systemService.findPageList(q);
		
		return AjaxJson.getOk(pageResult);
	}
	
	
	@RequestMapping("save")
	@ResponseBody
	public AjaxJson save(@RequestBody FarmWork work) {
		
		//编辑的时候，更新状态
		if(!StringUtils.isEmpty(work.getId())) {
			FarmWork target = this.systemService.findById(work.getId(), FarmWork.class);
			if(target.getState() == null && target.getUser() == null) {
				work.setState(1);
			}else if(target.getUser() != null && target.getState() != null && target.getState().equals(1)) {
				work.setState(2);
			}
		}
		
		
		this.systemService.save(work);
		return AjaxJson.getOk("保存成功");
	}
	
	@RequestMapping("delete")
	@ResponseBody
	public AjaxJson delete(@RequestBody FarmWork work) {
		this.systemService.delete(work);
		return AjaxJson.getOk("删除成功");
	}
	
	
	@RequestMapping("calendarList")
	@ResponseBody
	@JsonView(JsonViews.FarmWorkList.class)
	public AjaxJson calendarList(String theDate) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM");
		try {
			Date begin = sdf.parse(theDate);
			Calendar c = Calendar.getInstance();
			c.setTime(begin);
			c.add(Calendar.MONTH, 1);
//			c.add(Calendar.DATE, -1);
			Date end = c.getTime(); 
			
			System.out.println(begin);
			System.out.println(end);
			
			Query<FarmWork> q = Query.create(FarmWork.class);
			q.between("beginDate",begin,end);
			List<FarmWork> pageResult =  systemService.findList(q);		
			return AjaxJson.getOk(pageResult);

		} catch (ParseException e) {
			e.printStackTrace();
			return AjaxJson.getError("date parse error!");
		}
		
	}
	
	
}
